package modelo.bd;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import modelo.bd.excepcion.DAOException;
import modelo.io.FileException;
import modelo.io.ManejadorArchivos;

public class ConexionPool {

    private static ConexionPool instancia;
    private ComboPooledDataSource pool;
    private Properties config;

    private ConexionPool() throws DAOException {
        inicializar();
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return new CloneNotSupportedException("No se puede clonar ConexionPool.");
    }

    public static ConexionPool getInstancia() throws DAOException {
        if (instancia == null) {
            instancia = new ConexionPool();
        }
        return instancia;
    }

    public Connection getConexion() throws SQLException {
        return pool.getConnection();
    }

    private void inicializar() throws DAOException {
        try {
            config = ManejadorArchivos.instancia().obtenerArchivoPropiedades("../jdbc.properties");
            pool = new ComboPooledDataSource();
            pool.setDriverClass(config.getProperty("bd_driver"));
            pool.setJdbcUrl(config.getProperty("bd_url"));
            pool.setUser(config.getProperty("bd_usuario"));
            pool.setPassword(config.getProperty("bd_contrasena"));
            
            pool.setInitialPoolSize(Integer.parseInt(config.getProperty("bd_pool_ini")));
            pool.setMinPoolSize(Integer.parseInt(config.getProperty("bd_pool_min")));
            pool.setAcquireIncrement(Integer.parseInt(config.getProperty("bd_pool_acq")));
            pool.setMaxPoolSize(Integer.parseInt(config.getProperty("bd_pool_max")));
//            pool.setMaxStatements(Integer.parseInt(config.getProperty("bd_pool_max_stm")));
//            pool.setMaxStatementsPerConnection(Integer.parseInt(config.getProperty("bd_pool_max_stm_pcon")));
        } catch (FileException ex) {
            throw new DAOException(ex);
        } catch (PropertyVetoException ex) {
            throw new DAOException(ex);
        }
    }
}
